﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ComLib.ComFun;
using System.IO;

namespace FRPrinter
{
    public partial class FormConfig : Form
    {
        private FRPOption _option = new FRPOption();

        private List<string> _printers = new List<string>();
   

        public FormConfig()
        {
            InitializeComponent();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (UpdateData())
            {
                _option.Save();
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }          
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void LoadConfig()
        {
            if (!File.Exists(_option.ConfigFilePath))
            {
                _option.Save();
            }
            _option.Load();
        }

        private void FormConfig_Load(object sender, EventArgs e)
        {
            LoadConfig();
            InitCtrls();
        }

        private void InitCtrls()
        {  
           comboBoxPrinterList.Items.Clear();
            _printers = PrinterService.Printers;
            foreach (string name in _printers)
            {
                comboBoxPrinterList.Items.Add(name);
            }
            SelectPrinter(_option.Printer);   
            textBoxTemplateFile.Text = _option.TemplateFileName;
        }

        private bool SelectPrinter(string printer)
        {
            int i = _printers.IndexOf(printer);
            if (i != -1)
            {
                comboBoxPrinterList.SelectedIndex = i;
                return true;
            }
            return false;
        }

        private bool UpdateData()
        {
            if (comboBoxPrinterList.SelectedItem == null)
            {
                MessageBox.Show("没有选择有效的打印机!");
                return false;
            }
            _option.TemplateFileName = textBoxTemplateFile.Text;
            _option.Printer = comboBoxPrinterList.SelectedItem.ToString();
            return true;
        }
    }
}
